package com.web.web.config;

import com.web.farme.application.DefaultContext;
import com.web.farme.tool.StringUtils;
import com.web.web.annotation.ApiController;
import com.web.web.request.LoginInterceptor;
import com.web.web.request.SessionUserArugmentResolver;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebConfigurer implements WebMvcConfigurer {

    private final LoginInterceptor loginInterceptor;
    private final SessionUserArugmentResolver sessionUserArugmentResolver;
    private final WebConfig webConfig = DefaultContext.getConfig(WebConfig.class);

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.addPathPrefix(StringUtils.isNotBlank(this.webConfig.getPathPrefix()) ? this.webConfig.getConfigKey() : this.webConfig.getPrefix(),
                c -> c.isAnnotationPresent(ApiController.class));

        WebMvcConfigurer.super.configurePathMatch(configurer);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.loginInterceptor).addPathPatterns("/**");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(this.sessionUserArugmentResolver);
    }
}
